from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.views import View
import json
from django.http import *
from django_redis import get_redis_connection
from apps.goods.models import SKU
from utils.cookiesecret import CookieSecret
from utils.response_code import RETCODE


class CartsView(View):
    """购物车的增删改查"""
    def post(self, request):
        """购物车添加商品"""
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 判断参数是否齐全
        if not all([sku_id, count]):
            return HttpResponseForbidden('缺少必传参数')

        # 判断sku_id是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist as e:
            return HttpResponseForbidden('商品不存在')

        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return HttpResponseForbidden('参数count有误')

        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return HttpResponseForbidden('参数selected有误')

        # 判断用户是否登陆
        if request.user.is_authenticated:
            # 登陆使用 redis 存储
            carts_cli = get_redis_connection('carts')

            # 查询商品是否在购物车
            cart_data = carts_cli.hgetall(request.user.id)

            if not cart_data:
                # 不存在就创建新的数据
                carts_cli.hset(request.user.id, sku_id, json.dumps({'count': count, 'selected': selected}))
            # 更新数据 redis 数据库取出来的数据是 字节格式 比较数据格式 需要选择其一将其转换同种类型
            if str(sku_id).encode() in cart_data:
                old_count = json.load(cart_data[str(sku_id).encode()].decode()).get("count")
                count += old_count
                carts_cli.hset(request.user.id, sku_id, json.dumps({'count': count, 'selected': selected}))
            else:
                # 增加商品数据
                carts_cli.hset(request.user.id, sku_id, json.dumps({'count': count, 'selected': selected}))

            return JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
        else:
            # 查询 cookie 里面的购物车数据
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 解密 更新数据
                cart_dict = CookieSecret.loads(cart_str)
            else:
                # 新建 加密
                cart_dict = {}

            # 判断商品是否存在购物车
            if sku_id in cart_dict:
                count = cart_dict[sku_id]["count"]
                count += count
            # 数据更新
            cart_dict[sku_id] = {
                "count": count,
                "selected": selected
            }

            # 加密
            secret_cart = CookieSecret.dumps(cart_dict)
            # 获取响应对象
            response = JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
            # 设置 cookie
            response.set_cookie("carts", secret_cart, max_age=24 * 30 * 3600)

            return response

    def get(self, request):
        """购物车展示"""
        if request.user.is_authenticated:
            # 用户登陆 查询 redis 库
            cart_cli = get_redis_connection('carts')

            # 2.获取当前用户的 所有购物车数据
            carts_data = cart_cli.hgetall(request.user.id)

            # 3.转换格式-->和cookie一样的字典 方便后面构建数据
            carts_dict = {int(data[0].decode()): json.loads(data[1].decode()) for data in carts_data.items()}
            # dic = {'5': {count: 1, "selected":True}}
        else:
            # 未登录 查询 cookie
            cookie_str = request.COOKIES.get("carts")

            if cookie_str:
                # 存在 解密
                carts_dict = CookieSecret.loads(cookie_str)
            else:
                carts_dict = {}

        sku_ids = carts_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': carts_dict.get(sku.id).get('count'),
                'selected': str(carts_dict.get(sku.id).get('selected')),  # 将True，转'True'，方便json解析
                'default_image_url': sku.default_image.url,
                'price': str(sku.price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
                'amount': str(sku.price * carts_dict.get(sku.id).get('count')),
            })
        context = {
            'cart_skus': cart_skus,
        }

        # 渲染购物车页面
        return render(request, 'cart.html', context)

    def put(self, request):
        """购物车的修改"""
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get("sku_id")
        count = json_dict.get("count")
        selected = json_dict.get("selected", True)
        # 判断参数是否齐全
        if not all([sku_id, count]):
            return HttpResponseForbidden('缺少必传参数')
        # 判断sku_id是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseForbidden('商品sku_id不存在')
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return HttpResponseForbidden('参数count有误')
        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return HttpResponseForbidden('参数selected有误')

        secret_cart = ""
        if request.user.is_authenticated:
            #  1.链接 redis
            carts_redis_client = get_redis_connection('carts')
            # 2.覆盖redis以前的数据
            new_data = {'count': count, 'selected': selected}
            carts_redis_client.hset(request.user.id, sku_id, json.dumps(new_data))
        else:
            # 用户未登陆
            cart_str = request.COOKIES.get("carts")
            if cart_str:
                # 解密
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}

            cart_dict[sku_id] = {
                "count": count,
                "selected": selected
            }
            # 加密
            secret_cart = CookieSecret.dumps(cart_dict)

        # 构建前端的数据
        cart_sku = {
            'id': sku_id,
            'count': count,
            'selected': selected,
            'name': sku.name,
            'default_image_url': sku.default_image.url,
            'price': sku.price,
            'amount': sku.price * count,
        }
        response = JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
        if not request.user.is_authenticated:
            # 响应结果并将购物车数据写入到cookie
            response.set_cookie('carts', secret_cart, max_age=24 * 30 * 3600)
        return response

    def delete(self, request):
        """购物车的删除"""
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get("sku_id")

        # 判断商品是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist as e:
            return HttpResponseForbidden('商品不存在')

        # 判断用户是否登陆
        if request.user.is_authenticated:
            # 删除 redis 数据
            cart_cli = get_redis_connection("carts")
            cart_cli.hdel(request.user.id, sku_id)
            # 删除结束后，没有响应的数据，只需要响应状态码即可
            return JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
        else:
            # 删除 cookie 数据
            cart_str = request.COOKIES.get("carts")
            if cart_str:
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}

            # 创建响应对象
            response = JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})

            if sku_id in cart_dict:
                # 删除数据
                del cart_dict[sku_id]
                # 将字典转成密文
                secret_cart = CookieSecret.dumps(cart_dict)
                # 响应结果并将购物车数据写入到cookie
                response.set_cookie('carts', secret_cart, max_age=24 * 30 * 3600)
            return response


class SelectionCartsView(View):
    def put(self, request):
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get("selected", True)
        # 校验参数
        if selected:
            if not isinstance(selected, bool):
                return HttpResponseForbidden('参数selected有误')

        if request.user.is_authenticated:
            cart_cli = get_redis_connection("carts")
            cart_skus = cart_cli.hgetall(request.user.id)
            for cart_sku in cart_skus.items():
                sku_id = cart_sku[0].decode()
                cart_dict = json.loads(cart_sku[1].decode())
                cart_dict['selected'] = selected

                cart_cli.hset(request.user.id, sku_id, json.dumps(cart_dict))
            return JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
        else:
            # 未登录 进行 cookies 操作
            cart_str = request.COOKIES.get("carts")
            response = JsonResponse({'code': RETCODE.OK, 'errmsg': '全选购物车成功'})
            if cart_str is not None:
                cart_dict = CookieSecret.loads(cart_str)
                for sku_id in cart_dict:
                    cart_dict[sku_id]["selected"] = selected
                secret_cart = CookieSecret.dumps(cart_dict)
                response.set_cookie("carts", secret_cart, max_age=24 * 3600 * 30)
            return response


class SimpleCartsView(View):
    def get(self, request):
        # 判断用户是否登陆
        if request.user.is_authenticated:
            client = get_redis_connection("carts")
            redis_data = client.hgetall(request.user.id)
            carts_dict = {int(sku_id.decode()): json.loads(cart_dict.decode()) for sku_id, cart_dict in redis_data.items()}
        else:
            cookie_str = request.COOKIES.get("carts")
            if cookie_str:
                carts_dict = CookieSecret.loads(cookie_str)
            else:
                carts_dict = {}
        # 构造数据
        cart_skus = []
        sku_ids = carts_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': carts_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image.url
            })
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'cart_skus': cart_skus})




